from datetime import datetime

from ActionBase import ActionBase
from ActionExceptions import *
from Response import Response

from django.conf import settings

from chat.model.Action import Action
from chat.model.User import User


class ActionGetEvents(ActionBase):
    _action_token = 'get_events'

    _TARGET_KEY = 'targets[]'
    _UPDATE_KEY = 'update_key'

    def handle(self, postData):
        response = Response()

        # By default get from the main channel ''
        actionTargets = postData.getlist(self._TARGET_KEY)
        actionUpdateKey = postData.get(self._UPDATE_KEY, None)

        actionUser = User.verify_message(postData.get(self._USER_ID_TOKEN, None), postData.get(self._MESSAGE_KEY_TOKEN, None), postData.get(self._MESSAGE_HASH_TOKEN, None))
        if actionUser is None:
            raise ActionIntegrityException()

        actionChannels = []

        if len(actionTargets) > 0:
            for actionTarget in actionTargets:
                actionChannel = User.verify_target(actionUser, actionTarget)
                if actionChannel is None:
                    raise TargetException()

                actionChannels.append(actionChannel)
        else:
            actionChannels = [x for x in actionUser.channels.all()]
        response._data = {"actions": ActionGetEvents.get_actions(actionUser, actionChannels, actionUpdateKey)}
        return response
    
    @classmethod
    def get_actions(cls, user, targets, update_key):
        # Get the last number of actions pertinent to the target channel and timestamp   
        return Action.objects.\
                filter(action__in=['DISCONNECT', 'JOIN', 'NICK', 'PART', 'PRIVATETALK', 'TALK', 'SELFTALK']).\
                filter(target__in=targets).\
                filter(id__gt=update_key).\
                order_by('-timestamp')[0:settings.PCDM_MESSSAGE_LIMIT]
  
